<template>
  <div class="app-container">
    <div class="table">
      <el-form class="search-container" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="所属分组" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入所属分组" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="毕设名称" prop="teamName">
          <el-input v-model="queryParams.teamName" placeholder="请输入毕设名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="学生学号" prop="stuId">
          <el-input v-model="queryParams.stuId" placeholder="请输入学生学号" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="学生名字" prop="studentName">
          <el-input v-model="queryParams.studentName" placeholder="请输入学生名字" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="指导老师" prop="teacherName">
          <el-input v-model="queryParams.teacherName" placeholder="请输入指导老师名字" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="是否分配" prop="isAssigned">
          <el-select v-model="queryParams.isAssigned" placeholder="请选择是否分配" clearable style="width: 200px" @change="handleQuery">
            <el-option label="已分配" value="1" />
            <el-option label="未分配" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table-container">
        <el-row :gutter="10" class="mb8">
          <span>队伍信息表</span>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
            add="system:team:add"
            @handleAdd="handleAdd"
            del="system:team:remove"
            @handleDelete="handleDelete"
            exp="system:team:export"
            @handleExport="handleExport"
            :single="single"
            :multiple="multiple"
          ></right-toolbar>
        </el-row>
        <el-table v-loading="loading" class="table-content" border :data="teamList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="所属分组" align="center" prop="group.groupName" />
          <el-table-column label="毕设名称" align="center" prop="teamName" />
          <el-table-column label="毕设" align="center">
            <template #default="{ row }">
              <el-link v-if="row.teamLink" :href="row.teamLink" target="_blank" type="primary">查看</el-link>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="指导老师" align="center">
            <template #default="{ row }">
              <span v-if="row.teamTeachers.length > 0 && row.teamTeachers[0].selectFlag == '1'">{{ row.teamTeachers[0].teacher.user.nickName }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="队伍详情" align="center">
            <template #default="{ row }">
              <span style="cursor: pointer; color: var(--el-color-primary)" @click="handleViewTeam(row)">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center">
            <template #default="{ row }">
              <span>{{ parseTime(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="{ row }">
              <div v-if="!isAfterGroupTime(row.group?.endTime)">
                <el-button v-if="!isAssigned(row)" link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:team:edit']">修改</el-button>
                <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:team:remove']">删除</el-button>
              </div>
              <span v-else style="color: #999; font-size: 12px">已结束</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="pagination-container" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>

    <index-dialog ref="dialogRef" @update="updateHandler"></index-dialog>
    <team-detail-dialog ref="teamDetailDialogRef"></team-detail-dialog>
  </div>
</template>

<script setup name="Team">
import { listTeam, getTeam, delTeam, addTeam, updateTeam } from '@/api/team'
import { getCurrentInstance, ref } from 'vue'
import { useRouter } from 'vue-router'
import indexDialog from './components/indexDialog.vue'
import TeamDetailDialog from './components/TeamDetailDialog.vue'
const { proxy } = getCurrentInstance()
const router = useRouter()

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const teamList = ref([])
const dialogRef = ref(null)
const queryRef = ref(null)
const teamDetailDialogRef = ref(null)
const queryHandler = () => {
  queryParams.value.pageNum = 1
  getList()
}

const getList = () => {
  loading.value = true
  listTeam(queryParams.value).then(({ data }) => {
    teamList.value = data.rows
    total.value = data.total
    loading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.teamId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryHandler()
}
/** 修改按钮操作 */
const handleUpdate = (row) => {
  const teamId = row?.teamId || ids.value
  if (!teamId) {
    proxy.$modal.msgError('请选择要修改的数据')
    return
  }

  // 跳转到修改页面，传递 teamId 参数
  router.push({
    path: '/team/create',
    query: {
      teamId: teamId,
      groupId: row?.groupId,
      deptId: row?.group?.deptId,
      gradeId: row?.group?.gradeId,
      mode: 'edit'
    }
  })
}
/** 新增按钮操作 */
const handleAdd = () => {
  if (!dialogRef.value || typeof dialogRef.value.openDialog !== 'function') {
    console.warn('对话框尚未就绪，稍后重试')
    return
  }
  dialogRef.value.openDialog()
}
/** 删除按钮操作 */
const handleDelete = (row) => {
  const teamId = row?.teamId || ids.value
  proxy.$modal
    .confirm('是否确认删除编号为"' + teamId + '"的数据项?')
    .then(function () {
      return delTeam(teamId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const updateHandler = () => {
  queryHandler()
}
const handleExport = () => {
  proxy.download('system/team/export', { ...queryParams.value }, `team_${new Date().getTime()}.xlsx`)
}

// 查看队伍详情
const handleViewTeam = (row) => {
  if (!teamDetailDialogRef.value) {
    console.warn('队伍详情弹窗组件未加载')
    return
  }
  teamDetailDialogRef.value.openDialog(row)
}

// 分配操作按钮事件（占位实现，可接入后端接口）
const onAutoAssign = () => {
  proxy.$modal.msgInfo('已触发自动分配（占位），请接入后端接口')
}
const onManualAssign = () => {
  // 这里采用弹窗手动编辑队伍信息，后续可定制为分配老师弹窗
  dialogRef.value?.openDialog()
}
getList()

// 判断当前时间是否大于分组结束时间
const isAfterGroupTime = (endTime) => {
  if (!endTime) return false
  return new Date() > new Date(endTime)
}

// 判断队伍是否已分配（有老师被选中）
const isAssigned = (row) => {
  if (!row.teamTeachers || row.teamTeachers.length === 0) {
    return false
  }
  return row.teamTeachers.some((teacher) => teacher.selectFlag === '1')
}
</script>
<style scoped>
.assign-actions {
  margin-left: 12px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
</style>
